#include <avr/io.h>
#include <util/delay.h>

void wait(int a)
{
int i,j;
for(i=0;i<a;i++)
	for(j=0;j<4;j++)
		_delay_ms(25);
}

void init(void)
{
DDRA=0x00;//set point
DDRB=0x00;//leds
PORTB=0xFF;
DDRC=0xFF;//input sensors
DDRD=0xFF;//relay
}

int adcdata(void)
{
	ADMUX=0xE0;
	ADCSRA=0xC3;
	while((ADCSRA&0x40)!=0x00);
	return ADCH;
}

int setpoint(void)
{
int setpoint,data;

	 data=adcdata();
	 if(data<(32*1))
		{
		 setpoint=1;
//		 PORTB=0b00000001;
		}
	 else if(data<(32*2))
		{
		 setpoint=2;
//		 PORTB=0b00000010;
		}
	 else if(data<(32*3))
		{
		 setpoint=3;
		 //PORTB=4;
		}
	 else if(data<(32*4))
		{
		 setpoint=4;
		 //PORTB=8;
		}
	 else if(data<(32*5))
		{
		 setpoint=5;
		 //PORTB=16;
		}
	 else if(data<(32*6))
		{
		 setpoint=6;
		 //PORTB=0x20;
		}
	 else if(data<(32*7))
		{
		 setpoint=7;
		 //PORTB=0x40;
		}
	 else if(data<(32*8))
		{
		 setpoint=8;
		 //PORTB=0x80;
		}
return setpoint;
}

int sens(void)
{
int s;
if(((~PINB)&0x00)==0x00)
	{s=0;
	}

if(((~PINB)&0x01)==0x01)
	{s=1;
	}

if(((~PINB)&0x02)==0x02)
	{s=2;
	}

if(((~PINB)&0x04)==0x04)
	{s=3;
	}

if(((~PINB)&0x08)==0x08)
	{s=4;
	}

if(((~PINB)&0x10)==0x10)
	{s=5;
	}

if(((~PINB)&0x20)==0x20)
	{s=6;
	}

if(((~PINB)&0x40)==0x40)
	{s=7;
	}

if(((~PINB)&0x80)==0x80)
	{s=8;
	}

return s;
}

int main(void)
{
init();
while(1)
	{
if(sens()<setpoint())
	PORTD=0x01;
if(sens()>setpoint())
	PORTD=0x02;
if(sens()==setpoint())
	PORTD=0x04;
     wait(1);
	}

return 0;
}
